package com.zlf.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zlf.constant.CrowdConstant;
import com.zlf.dao.AdminMapper;
import com.zlf.entity.Admin;
import com.zlf.entity.AdminExample;
import com.zlf.exception.LoginAcctAlreadyInUseException;
import com.zlf.exception.LoginFailedException;
import com.zlf.exception.UpdateFailedException;
import com.zlf.service.api.AdminService;
import com.zlf.util.CrowdUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author ：张利锋
 * @date ：Created in 2020/11/11 15:00
 * @description： TOOD
 * @version: 1.0
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Override
    public void saveAdmin(Admin admin) {
        //1.密码加密
        String md5 = passwordEncoder.encode(admin.getUserPswd());
        admin.setUserPswd(md5);
        //2.生成时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = dateFormat.format(date);
        admin.setCreateTime(createTime);
        //3.执行保存
        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGINACCT_DUPLICATE);
            } else {
                LoggerFactory.getLogger(AdminServiceImpl.class).info("我是增加用户时的其他异常");
            }
        }


    }

    @Override
    public void deleteByPrimaryKey(Integer id) {
        adminMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Admin> findAll() {
        List<Admin> admins = adminMapper.selectByExample(new AdminExample());
        return admins;
    }

    @Override
    public List<Admin> getAdminByLoginAcct(String loginAcct) {
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> admins = adminMapper.selectByExample(example);
        return admins;
    }

    @Override
    public Admin getAdminByLoginAcct(String loginAcct, String userPswd) {
        //1.根据登录表单查询admin对象
        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginAcctEqualTo(loginAcct);
        List<Admin> admins = adminMapper.selectByExample(example);
        //2.判断admins是否为null
        if (admins == null || admins.size() == 0) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        if (admins.size() > 1) {
            throw new RuntimeException(CrowdConstant.MESSAGE_LOGINACCT_DUPLICATE);
        }
        Admin admin = admins.get(0);
        //3.如果admin对象为null
        if (admin == null) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        //4.取出数据库密码
        String adminUserPswd = admin.getUserPswd();
        //5.把表单密码md5加密后进行比较
        String md5Pswd = CrowdUtil.encryptMd5(userPswd);
        //6.不相等则密码错误
        if (!Objects.equals(adminUserPswd, md5Pswd)) {
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);
        }
        //7.如果正确则返回admin
        return admin;
    }



    @Override
    public PageInfo<Admin> selectAdminListByKeyword(String keyword, Integer pageNum, Integer pageSize) {

        //1.开启分页功能
        PageHelper.startPage(pageNum, pageSize);
        //2.执行查询
        List<Admin> admins = adminMapper.selectAdminListByKeyword(keyword);
        //3.封装到pageinfo
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        return pageInfo;
    }

    @Override
    public Admin getAdminById(Integer adminId) {
        Admin admin = adminMapper.selectByPrimaryKey(adminId);
        return admin;
    }

    @Override
    public void updateAdmin(Admin admin) {
        try {
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            throw new UpdateFailedException(CrowdConstant.MESSAGE_LOGINACCT_DUPLICATE);
        }
    }

    @Override
    public void insertAdminRoleRelationship(Integer adminId, List<Integer> roleList) {
        //先移除现有role
        adminMapper.removeRelationshipByAdminId(adminId);
        if (roleList != null && roleList.size() > 0) {
            //再重新添加role
            adminMapper.addRelationship(adminId, roleList);
        }
    }
}
